<template>
  <div class="page-container">
    <section class="flex offset-fotm-item">
      <div>
        <el-form @submit.prevent="search" inline>
          <el-form-item label="查询">
            <el-input placeholder="学号"  v-model="searchForm.sno"/>
          </el-form-item>
          <el-form-item label="性别">
            <el-select placeholder="全部" style="width:100px;" v-model="searchForm.sex">
              <el-option :value="0" label="全部"></el-option>
              <el-option :value="1" label="男"></el-option>
              <el-option :value="2" label="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="search" type="primary">查询</el-button>
            <el-button @click="showBulkAssian" type="primary">批量分配宿舍</el-button>
            <el-button type="success" @click="exportExcel">
            <el-icon><Download /></el-icon>导出 Excel 表格
          </el-button>
          </el-form-item>
        </el-form>
      </div>
    </section>

    <el-table :data="studentData"
              :default-sort="{prop: 'SNO', order: 'ascending'}"
              @selection-change="onSelectionChange"
              border
              v-loading="loading"
              stripe
              :header-cell-style="{backgroundColor:'aliceblue',color:'#666'}"
    >
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="学号" prop="SNO" sortable/>
      <el-table-column align="center" label="姓名" prop="SNAME" />
      <el-table-column :formatter="dormState" align="center" label="入住状态" prop="DORMSTATE" sortable/>
      <el-table-column align="center" label="性别" prop="SSEX" sortable/>
      <el-table-column :formatter="dormConvert" align="center" label="宿舍号" prop="DORM_ID" sortable/>
      <el-table-column align="center" label="专业" prop="MAJOR_NAME" />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-tooltip content="学生信息">
            <el-button @click="showStudentDetail(scope.row)" circle plain>
            <el-icon><User /></el-icon>
           </el-button>
          </el-tooltip>
          <el-tooltip content="学生宿舍管理">
            <el-button @click="showAssignDorm(scope.row)" circle plain>
              <el-icon><OfficeBuilding /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="studentData?.length || 0"
      @current-change="handlePageChange"
      style="margin-top: 20px;"
    ></el-pagination>
    
    <!-- 学生信息 -->
    <student-detail :info="curStudentDetail" v-model="isShowStudentDetail"/>

    <!-- 学生宿舍管理 -->
    <assign-student-dorm :curStudentDetail="curStudentDetail"
                  v-model="isShowAssignDorm"
                  @update:isShowAssignDorm="handleUpdate"/>
      <!-- 批量分配宿舍  -->
      <bulk-assign-dorm :selected-students="selectedStudents"  v-model="isShowBulkAssian" @showBulkAssianEvent="handleShowBulkAssianEvent" @update="getData"/>
    </div>
  </template>
  
<script>
import AssignStudentDorm from "@/components/student/assign-student-dorm";
import StudentDetail from "@/components/student/student-detail";
import BulkAssignDorm from "@/components/student/bulk-assign-dorm";
import {ShowStu,SearchStu} from '@/api/index/admin';
import * as XLSX from 'xlsx';

  export default {
    components: {StudentDetail, AssignStudentDorm,BulkAssignDorm},
    data() {
      return {
        loading: true,
        startIndex: 0,
        endIndex: 10, // 每页显示数量
        currentPage: 1, // 当前页码
        pageSize: 10, // 每页显示数量
        searchForm: {
          sno: "",
          sex: 0
        },
        studentData: [],
        isShowStudentDetail:false,
        isShowModifyStudent: false,
        curStudentDetail: {},
        isShowAssignDorm: false,
        selectedStudents: [],
        isShowBulkAssian: false
      }
    },
    created(){
      this.getData();
    },
    methods: {
      handlePageChange(newPage) {
        this.currentPage = newPage;
        this.startIndex = (newPage - 1) * this.pageSize;
        this.endIndex = this.startIndex + this.pageSize;
      },
      search() {
        this.startIndex = 0; // 重置起始索引为第一页
        this.endIndex = this.pageSize; // 重置结束索引为每页显示数量
        if (this.searchForm) {
          const params = { id: this.searchForm };
          SearchStu(params).then((res) => {
            if (res.data && res.data.data && res.data.data.length > 0) {
              this.studentData = res.data.data;
            } else {
              this.studentData = []; // 清空表格数据
            }
          })
          .catch((error) => {
            console.error('Failed to search data:', error);
          });
        } else {
          this.getData(); // 显示全部数据
        }
      },
      getData() {
        this.loading = true;
        ShowStu().then(res=>{
          this.studentData = res.data.data;
          console.log(res.data.data);
          this.loading = false;
        })
      },
      exportExcel() {
        const excelData = this.studentData.map((item) => ({
          '学号': item.SNO,
          '姓名': item.SNAME,
          '入住状态': this.dormState(item.DORMSTATE),
          '性别': item.SSEX === 1 ? '男' : '女',
          '宿舍号': item.DORMSTATE === 1 ? item.DORM_ID: '未入寝',
          '专业': item.MAJOR_NAME,
        }));
        const ws = XLSX.utils.json_to_sheet(excelData);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '学生住宿信息');
        XLSX.writeFile(wb, '学生住宿信息.xlsx');
      },
      onSelectionChange(selection) {
        this.selectedStudents = selection;
      },
      showStudentDetail(row){
        this.curStudentDetail = row;
        this.isShowStudentDetail = true;
      },
      showAssignDorm(row){
        this.curStudentDetail = row;
        this.isShowAssignDorm = true;
      },
      sexConvert(row, column, v) {
        return v == 1 ? "男" : v == 2 ? "女" : ""
      },
      dormConvert(row, column, v) {
        if (row.DORMSTATE === 1) {
          return v
        }
        if (row.DORMSTATE === -1) {
          return "未入寝"
        }
        if (row.DORMSTATE === 2) {
          return "已退寝"
        }
      },
      dormState(row) {
        if (row.DORMSTATE === 1) {
          return "已入寝"
        }
        if (row.DORMSTATE === -1) {
          return "未入寝"
        }
        if (row.DORMSTATE=== 2) {
          return "已退寝"
        }
      },
      // 监听子组件的更新事件
      handleUpdate() {
        this.isShowAssignDorm = false;
      },
      showBulkAssian() {
        // 判断是否选择了学生
        console.log(this.selectedStudents)
        if (this.selectedStudents.length <= 0) {
            this.$message.warning("请先选择学生");
          return false;
        }
        // console.log("Clicked on showBulkAssian");
        this.isShowBulkAssian = true;
        // console.log(this.isShowBulkAssian)
        
      },
      handleShowBulkAssianEvent(){
        this.isShowBulkAssian = false;
      },
      },
      mounted() {
        this.getData();
      },
    }
  </script>